#!/usr/bin/env python
# coding=utf-8

import requests
# from bs4 import BeautifulSoup
import json
import re
import os
# 'ascii' codec can't encode characters
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

class BaiduMusicDownload(object):

    def __init__(self):
        self.__BASE_URL = r'http://music.baidu.com/songlist/{album_id}'
        self.__SONG_DATA_URL = r'http://music.baidu.com/data/music/fmlink?songIds='
        self.__SONG_SEARCH_URL = None
        self.__SONG_REAL_DATA = None
        self.__SONG_REAL_URL = None 

        # Song info
        self.__SONG_ID = None
        self.__SONG_NAME = None
        self.__SONG_AUTHOR = None
        self.__SONG_FORMAT = None
        self.__SONG_ALBUM = None

        # song list
        self.__SONG_LIST = None

    def get_song_id(self, album_id):
        self.__SONG_SEARCH_URL = self.__BASE_URL.format(album_id=album_id)

        req = requests.get(self.__SONG_SEARCH_URL)
        song = req.content

        song_id_all = re.findall(r'<a href="/song/([^"]+)"', str(song))

        if len(song_id_all) == 0:
            return False
        
        self.__SONG_ID = song_id_all
        return song_id_all

    def get_real_song_data(self, song_id):
        data_url = self.__SONG_DATA_URL+str(song_id)
        req = requests.get(data_url)

        song_data = json.loads(str(req.content))['data']
        if song_data != '':
            songList = song_data['songList'][0]
            self.__SONG_NAME = songList['songName']
            self.__SONG_AUTHOR = songList['artistName']
            self.__SONG_FORMAT = songList['format']
            self.__SONG_ALBUM = songList['albumName']
            self.__SONG_REAL_URL = songList['songLink']
        
        self.__SONG_REAL_DATA = song_data
        return self.__SONG_REAL_DATA

            
    def download_song(self, album_id):
        # @TODO
        self.__SONG_LIST = re.findall(r'<h2>([^"]+)</h2>', requests.get(self.__BASE_URL.format(album_id=album_id)).content)[0]
        self.__SONG_LIST = self.__SONG_LIST.strip()

        if not self.__SONG_LIST:
            from datetime import date
            self.__SONG_LIST = str(date.today())

        if not os.path.exists(self.__SONG_LIST):
            os.mkdir(self.__SONG_LIST.strip())
        os.chdir(self.__SONG_LIST)
        print self.__SONG_LIST

        start = 0
        i = 1
        while start < 20:
            self.get_song_id(album_id)
            for song_id in self.__SONG_ID:
                self.get_real_song_data(song_id)
               
                mp3Name = "{songName}--{author}.{format}".format(
                    songName = self.__SONG_NAME,
                    author = self.__SONG_AUTHOR,
                    format = self.__SONG_FORMAT,
                 )

                mp3Name = mp3Name.replace('/', '+')
                
                if os.path.isfile(mp3Name):
                    print "\t{0} 已存在..".format(mp3Name)
                    continue

                # download mp3
                req = requests.get(self.__SONG_REAL_URL)

                mp3file = open(mp3Name, 'wb')
                mp3file.write(req.content)
                mp3file.close()

                print '\t' + str(i) + ' ' +mp3Name
                i += 1

            start += 20

        os.chdir('..')

if __name__ == '__main__':
    import sys
    
    if len(sys.argv) == 1:
        print "Usage:"
        print "\t{filename} Artist".format(filename=sys.argv[0])
        print "\t{filename} Artist1 Artist2 ...".format(filename=sys.argv[0])
        exit(False)

    download = BaiduMusicDownload()
    for song in sys.argv:
        if song == sys.argv[0]:
            continue
        download.download_song(song)
